/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var async  = require( 'async'); // 同步控制


// Schema 结构
var ItbTmplPriceModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`price_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '项目id',
  //`type` int(3) NOT NULL COMMENT '模版类型(大分类): 1海报 2多页 3ppt',
  //`tmpl_id` bigint(20) NOT NULL COMMENT '模版id',
  //`price` bigint(20) NOT NULL COMMENT '价格（单位分）',
  //`period` bigint(10) NOT NULL DEFAULT '0' COMMENT '有效期（单位天）',
  //`free` int(1) NOT NULL DEFAULT '0' COMMENT '0需付费, 1限时免费',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) DEFAULT NULL,
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
ItbTmplPriceModel.prototype = new ItbBaseModel();

// 取得表名
ItbTmplPriceModel.prototype.getTableName = function(){
    return 'itb_tmpl_price';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbTmplPriceModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'price_id='+this.price_id;
}

// 查找模版价格信息
// 参数 type: 1单页, 2多页, 3ppt
// 参数 tmplId: 模版id
ItbTmplPriceModel.prototype.findPriceInfoByType = function(type,tmplId,skipCnt,pageSize,callback){
    var THIS = this;
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = ' SELECT tt.* FROM ( ';
        if(type==3){
            // ppt
            sql += " select p.* "+
                " FROM `itb_tmpl_price` p, `itb_template` t "+
                " WHERE p.del_flg=0 AND p.type="+type+
                " AND t.tmpl_id=p.tmpl_id AND t.del_flg=0 AND t.publish=1 ";

        } else if(type==1 || type==2){
            // 单页, 多页
            sql += " select p.* "+
                " FROM `itb_tmpl_price` p, `tg_design_doc` t "+
                " WHERE p.del_flg=0 AND p.type="+type+
                " AND t.design_id=p.tmpl_id AND t.del_flg=0 AND t.publish=1 ";

        } else {
            connection.release();
            return callback('参数错误', null);
        }

        if(tmplId && Number(tmplId||0)>0) {
            sql += " AND p.tmpl_id="+tmplId;
        }
        sql += " ORDER BY p.tmpl_id, p.price ) tt ";

        if(typeof skipCnt!='undefined' && skipCnt != null && typeof pageSize!='undefined' && pageSize != null){
            sql += " limit " + Number(skipCnt) + "," + Number(pageSize);
        }

        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });
}

// 导出
module.exports = ItbTmplPriceModel;